import org.openscience.cdk.renderer.font.AWTFontManager
import org.openscience.cdk.renderer.generators.BasicAtomGenerator
import org.openscience.cdk.renderer.generators.BasicBondGenerator
import org.openscience.cdk.renderer.generators.BasicSceneGenerator
import org.openscience.cdk.renderer.visitor.AWTDrawVisitor
import org.openscience.cdk.tools.LoggingToolFactory

module Mol
  class Renderer

    # Creates a new Mol::Renderer using the specified MDL Molfile. This renderer
    # can be used to render the molfile in bitmap formats.
    def initialize(mol_file)
      @molecule = Mol::Molecule.parse_mol_file(mol_file)
    end

    # Renders the molecule in PNG format. The returned array (ruby string) can
    # then be saved to a file, or maybe even be streamed from a web server.
    def to_png(width, height)
      image = render(width, height)
      output = java.io.ByteArrayOutputStream.new
      javax.imageio.ImageIO.write(image, "PNG", output)
      String.from_java_bytes(output.to_byte_array)
    end

    private

    # Renders the molecule to a java.io.BufferedImage.
    def render(width, height)
      # Adapted from http://sourceforge.net/apps/mediawiki/cdk/index.php?title=Renderer_Tutorial-Single_Molecules
      draw_area = java.awt.Rectangle.new(width, height)
      image = java.awt.image.BufferedImage.new(width, height, java.awt.image.BufferedImage::TYPE_INT_RGB)

      generators = java.util.ArrayList.new
      generators.add BasicSceneGenerator.new
      generators.add BasicBondGenerator.new
      generators.add BasicAtomGenerator.new

      renderer = org.openscience.cdk.renderer.Renderer.new(generators, AWTFontManager.new)
      renderer.setup(@molecule, draw_area)

      graphics = image.get_graphics
      graphics.set_color(java.awt.Color::WHITE)
      graphics.fill_rect(0, 0, width, height)

      renderer.paint_molecule(@molecule, AWTDrawVisitor.new(graphics), draw_area, true)

      image
    end
  end
end
